package com.apes.scm.masterdata.merchant.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.BranchRepository;
import com.apes.scm.masterdata.frame.repository.ContactsRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.merchant.model.Merchant;
import com.apes.scm.masterdata.merchant.repository.MerchantRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Title: BusinessCircleService
 * @Description: 商户信息
 * @author: Zhangwencong
 * @create: 2022/4/26 14:15
 */
@Service("merchantService")
public class MerchantService extends DomainService {

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private ContactsRepository contactsRepository;


    //保存方法
    public Merchant save(SimpleRequest request) {
        return update(request);
    }

    //修改方法
    public Merchant update(SimpleRequest request) {
        JSONObject jo = request.getJO();
        jo.remove("storeInfo");
        Merchant merchant = Tools.map(jo,Merchant.class);
        return merchantRepository.saveAndFlush(merchant);

    }

    //删除方法
    public String delete(SimpleRequest request) {
        String  id = request.get("id");
        Merchant merchant = merchantRepository.findOne(id);
        if (merchant == null) throw new RuntimeException("商户ID：" + request.get("id") + " 在系统中不存在。");
        merchantRepository.delete(merchant);
        return "删除成功！";
    }

    public Merchant findOne(String id) {
        return merchantRepository.findOne(id);
    }

    public boolean isSpecialChar(String str) {

        String regEx = "[ _`[email protected]#$%^&*()+=|{}‘:;‘,\\[\\].<>/?~！@#￥%……&*()——+|{}【】‘；：”“’。，、？]|\n|\r|\t";

        Pattern p = Pattern.compile(regEx);

        Matcher m = p.matcher(str);

        return m.find();

    }


   /* // 因有效查询条件比较特殊, 造此方法特殊查询
    public Page<Merchant> findAll(SimpleRequest request) throws Exception {
        List<Map> filters = request.get("condition");
        for (int i = 0; i < filters.size(); i++) {
            Map filter = filters.get(i);
            String field = filter.get("field").toString();
            String value = filter.get("value").toString();
            if ("validCondi".equals(field)) {
                if ("0".equals(value)) {
                    filter.put("value", false);
                    filter.put("field", "valid");
                }
                if ("1".equals(value)) {
                    filter.put("value", true);
                    filter.put("field", "valid");
                }
                if ("9".equals(value)) filters.remove(i);
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return merchantRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }*/



    /**
     * 查询出商户和门店信息
     * @param request
     * @return
     */
    public  Page<Merchant> findMerchantAnditem(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        for (int i = 0; i < filters.size(); i++) {
            Map filter = filters.get(i);
            String field = filter.get("field").toString();
            String value = filter.get("value").toString();
            if ("validCondi".equals(field)) {
                if ("0".equals(value)) {
                    filter.put("value", false);
                    filter.put("field", "valid");
                }
                if ("1".equals(value)) {
                    filter.put("value", true);
                    filter.put("field", "valid");
                }
                if ("9".equals(value)) filters.remove(i);
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Page<Merchant> merchants = merchantRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));


        return merchants;
    }


    public JSONArray getStoreInfo(Merchant merchant){
        JSONArray result = new JSONArray();
        List<Store> stores = SpringManager.getBean(StoreRepository.class).findAllByMerchant(merchant);
        if (stores==null)return null;
        stores.forEach(store -> {
            List<PartyRole> partyRoleList = this.invoke("aut.user.findAdministrator", MapUtil.mapper("storeId", store.getCode()));
            result.add(MapUtil.mapper("name",store.getName(),"contacts",contactsRepository.findAllByStoreIdAndContactIn(store.getCode(),partyRoleList)));
        });
        return result;
    }

    public List<Map> findAllByCarControl(SimpleRequest request){
        String branchId = request.getBranchId();
        if (branchId!=null){
            Branch branch = SpringManager.getBean(BranchRepository.class).findOne(branchId);
            List<Dept> depts = SpringManager.getBean(DeptRepository.class).findByBranch(branch);
            if (!depts.isEmpty()){
                List<Store> storeList = SpringManager.getBean(StoreRepository.class).findAll(JpaDsl.toCriteria("dept", "IN", depts));
                List<Merchant> collect = storeList.stream().map(Store::getMerchant).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                if (!collect.isEmpty()){
                    return collect.stream().map(merchant -> mapper("id", merchant.getId(), "name", merchant.getName())).collect(Collectors.toList());
                }else {
                    List<Map> maps = Collections.singletonList(mapper("id", "none", "name", "无运营商"));
                    return maps;
                }
            }
        }

        List<Merchant> all = merchantRepository.findAll();
        List<Map> resultList = new ArrayList<>();
        List<Map> collect = all.stream().map(merchant -> mapper("id", merchant.getId(), "name", merchant.getName())).collect(Collectors.toList());
        resultList.add(mapper("id","all","name","全部"));
        resultList.add(mapper("id","none","name","无运营商"));
        resultList.addAll(collect);
        return resultList;
    }
}
